package blog.sys.service;

import blog.sys.dao.UserDao;
import blog.sys.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pub.dao.GeneralDao;

/**
 * Created by zzl on 2016-07-18.
 */
@Service
@Transactional(readOnly = true)
public class UserService {


    public User get(Integer userId) {
        User user = userDao.get(userId);
        return user;
    }

    /**
     * 使用账号获取用户信息
     *
     * @return
     */
    public User getUserByAccount(String acc) {
        String sql = "select u.* FROM t_user u where u.activation = 1 and (u.mobile = ? or u.email = ?) ORDER BY u.id DESC limit 1";
        User u = generalDao.queryValue(User.class, sql, acc, acc);
        return u;
    }

    /**
     * 判断是否之前已经有人注册过了
     *
     * @param mobile
     * @param email
     * @return
     */
    public boolean getUserByMobileOrEmail(String mobile, String email) {
        String sql = "select 1 from t_user u where u.mobile = ? or u.email = ? ORDER by u.id desc limit 1 ";
        return generalDao.queryValue(Integer.class, sql, mobile, email) != null;
    }


    /**
     * 判断昵称是否之前有人使用过
     *
     * @param nickname
     * @return
     */
    public boolean getUserByNickName(String nickname) {
        String sql = "select 1 from t_user u where u.nickname = ?";
        return generalDao.queryValue(Integer.class, sql, nickname) != null;
    }


    /**
     * 用户注册
     *
     * @param user
     */
    @Transactional
    public Integer userRegister(User user) {
        userDao.save(user);
        Integer id = user.getId();
        return id;
    }


    @Transactional
    public void onActivateCurrUserService(Integer userId) {
        String sql = "update t_user u set u.activation = 1 where u.id = ?";
        generalDao.execute(sql, userId);
    }

    @Autowired
    private UserDao userDao;

    @Autowired
    private GeneralDao generalDao;

}
